<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Fanqie;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;

class FanqieApiController extends Controller
{
    /**
     * 获取所有书籍列表（JSON格式）
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {
        try {
            $books = Fanqie::orderBy('created_at', 'desc')->get();
            
            return response()->json([
                'success' => true,
                'message' => '获取书籍列表成功',
                'data' => $books
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取书籍列表失败',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * 获取所有分类
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function categories()
    {
        try {
            // 从数据库中获取所有唯一的分类
            $categories = Fanqie::select('category')
                ->distinct()
                ->whereNotNull('category')
                ->get()
                ->map(function ($item) {
                    return [
                        'id' => $item->category,
                        'name' => $item->category
                    ];
                })
                ->toArray();
            
            return response()->json([
                'success' => true,
                'message' => '获取分类成功',
                'data' => $categories
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取分类失败',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * 创建新书籍
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        try {
            $validated = $request->validate([
                'title' => 'required|string|max:255',
                'author' => 'required|string|max:255',
                'description' => 'required|string',
                'price' => 'required|integer|min:0',
                'image' => 'nullable|string|max:500',
                'category' => 'required|string|max:100',
                'publisher' => 'required|string|max:255',
            ]);

            $book = Fanqie::create($validated);

            return response()->json([
                'success' => true,
                'message' => '书籍创建成功',
                'data' => $book
            ], 201);
        } catch (ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '创建书籍失败',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * 显示指定书籍详情
     *
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id)
    {
        try {
            $book = Fanqie::find($id);
            
            if (!$book) {
                return response()->json([
                    'success' => false,
                    'message' => '书籍不存在'
                ], 404);
            }

            return response()->json([
                'success' => true,
                'message' => '获取书籍详情成功',
                'data' => $book
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取书籍详情失败',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * 更新指定书籍
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $id)
    {
        try {
            $book = Fanqie::find($id);
            
            if (!$book) {
                return response()->json([
                    'success' => false,
                    'message' => '书籍不存在'
                ], 404);
            }

            $validated = $request->validate([
                'title' => 'sometimes|string|max:255',
                'author' => 'sometimes|string|max:255',
                'description' => 'sometimes|string',
                'price' => 'sometimes|integer|min:0',
                'image' => 'nullable|string|max:500',
                'category' => 'sometimes|string|max:100',
                'publisher' => 'sometimes|string|max:255',
            ]);

            $book->update($validated);

            return response()->json([
                'success' => true,
                'message' => '书籍更新成功',
                'data' => $book
            ], 200);
        } catch (ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '更新书籍失败',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * 删除指定书籍
     *
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        try {
            $book = Fanqie::find($id);
            
            if (!$book) {
                return response()->json([
                    'success' => false,
                    'message' => '书籍不存在'
                ], 404);
            }

            $book->delete();

            return response()->json([
                'success' => true,
                'message' => '书籍删除成功'
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '删除书籍失败',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * 搜索书籍
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function search(Request $request)
    {
        try {
            $query = $request->get('q');
            $category = $request->get('category');
            
            $books = Fanqie::query();
            
            if ($query) {
                $books->where(function($q) use ($query) {
                    $q->where('title', 'like', "%{$query}%")
                      ->orWhere('author', 'like', "%{$query}%")
                      ->orWhere('description', 'like', "%{$query}%");
                });
            }
            
            if ($category) {
                $books->where('category', $category);
            }
            
            $books = $books->orderBy('created_at', 'desc')->get();

            return response()->json([
                'success' => true,
                'message' => '搜索完成',
                'data' => $books
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '搜索失败',
                'error' => $e->getMessage()
            ], 500);
        }
    }
    
    /**
     * 上传图片
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function upload(Request $request)
    {
        try {
            // 记录请求信息用于调试
            \Log::info('图片上传请求:', [
                'has_file' => $request->hasFile('image'),
                'all_files' => $request->allFiles(),
                'input' => $request->all()
            ]);
            
            // 检查是否有文件上传
            if (!$request->hasFile('image')) {
                return response()->json([
                    'success' => false,
                    'message' => '未找到上传的图片文件',
                ], 422);
            }
            
            $image = $request->file('image');
            
            // 记录文件信息用于调试
            \Log::info('上传的文件信息:', [
                'original_name' => $image->getClientOriginalName(),
                'client_mime' => $image->getClientMimeType(),
                'mime_type' => $image->getMimeType(),
                'size' => $image->getSize(),
                'extension' => $image->getClientOriginalExtension(),
            ]);
            
            // 检查文件是否有效
            if (!$image->isValid()) {
                return response()->json([
                    'success' => false,
                    'message' => '上传的文件无效',
                ], 422);
            }
            
            // 检查文件大小 (2MB)
            if ($image->getSize() > 2 * 1024 * 1024) {
                return response()->json([
                    'success' => false,
                    'message' => '图片文件大小不能超过2MB',
                ], 422);
            }
            
            // 检查文件类型
            $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
            $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
            
            $clientMimeType = $image->getClientMimeType();
            $fileExtension = strtolower($image->getClientOriginalExtension());
            
            $isValidMimeType = in_array($clientMimeType, $allowedMimeTypes);
            $isValidExtension = in_array($fileExtension, $allowedExtensions);
            
            // 如果MIME类型检查失败，但扩展名正确，我们仍然允许上传
            if (!$isValidMimeType && !$isValidExtension) {
                return response()->json([
                    'success' => false,
                    'message' => '图片格式必须是jpeg、png、jpg或gif',
                ], 422);
            }
            
            // 生成文件名并保存
            $filename = time() . '_' . Str::random(10) . '.' . $fileExtension;
            $path = $image->storeAs('public/images', $filename);
            
            $url = Storage::url($path);
            
            \Log::info('图片上传成功:', ['url' => $url]);
            
            return response()->json([
                'success' => true,
                'message' => '图片上传成功',
                'data' => [
                    'url' => $url
                ]
            ], 200);
        } catch (ValidationException $e) {
            \Log::error('图片上传验证失败:', [
                'errors' => $e->errors(),
                'message' => $e->getMessage()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            \Log::error('图片上传异常:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => '图片上传失败: ' . $e->getMessage(),
            ], 500);
        }
    }
}